package gupao.concurrency.simuio;

import gupao.concurrency.utils.FutureUtil;
import gupao.concurrency.utils.ThreadPoolService;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SimuioMainTest {
    static String bizName = "simuio";
    static int concurrency = 64;
    static int partitionNum = concurrency;
    static int totalRunTimes = 100 * 100;
    static ThreadPoolExecutor executor =
            ThreadPoolService.createFixedThreadPool(bizName, concurrency);

    public static void main(String[] args) {
        int[] partitions = split();
        concurrentRun(partitions);
    }

    static void concurrentRun(int[] partitions) {
        List<Callable<Integer>> tasks = Arrays.stream(partitions).mapToObj(
                partition -> (Callable<Integer>) () -> {
                    for (int i = 0; i < partition; i++) {
                        SimuioService.io75();
                    }
                    return partition;
                }
        ).collect(Collectors.toList());
        long start = System.currentTimeMillis();
        List<Future<Integer>> fsList = tasks.stream().map(executor::submit)
                .collect(Collectors.toList());
        List<Integer> result = FutureUtil.waitFuturesComplete2(fsList);
        long timeCost = System.currentTimeMillis() - start;
        printResult(partitions,result);
        System.out.println("Concurrency: " + concurrency);
        System.out.println("time cost: " + timeCost);
    }

    static void printResult(int[] partitions, List<Integer> result){
        StringBuilder psb = new StringBuilder("Partitions[").append(partitionNum).append("]:");
        if(partitions.length >= 16){
            psb.append("\n");
        }
        for(int i = 1; i <= partitions.length; i++){
            psb.append(partitions[i-1]).append(",");
            if(i % 16 == 0 && i != partitions.length){
                psb.append("\n");
            }
        }
        System.out.println(psb.toString());
        psb.setLength(0);
        psb.append("Run Result: ");
        if(result.size() >= 16){
            psb.append("\n");
        }
        for(int i = 1; i <= result.size(); i++){
            psb.append(result.get(i-1)).append(",");
            if(i % 16 == 0 && i != result.size()){
                psb.append("\n");
            }
        }
        System.out.println(psb.toString());
    }

    static int[] split() {
        int[] rt = new int[partitionNum];
        int avg = totalRunTimes / partitionNum;
        int remain = totalRunTimes;
        for (int i = 0; i < partitionNum - 1; i++) {
            rt[i] = avg;
            remain = remain - avg;
        }
        rt[partitionNum - 1] = remain;
        return rt;
    }

}
